package com.alit.face.koala.service;

import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alit.face.koala.entity.KoalaHost;
import com.alit.face.koala.repository.KoalaHostRepository;

/**
 * @author litong
 * @date 2019年4月27日_下午2:36:37
 * @version 1.0
 */
@Service
public class KoalaHostService {

  @Autowired
  private KoalaHostRepository koalaHostRepository;

  /**
   * 根据IP查询
   * 
   * @param ip
   * @return
   */
  @SuppressWarnings("serial")
  public KoalaHost findByIP(String ip) {
    Specification<KoalaHost> specification = new Specification<KoalaHost>() {

      @Override
      public Predicate toPredicate(Root<KoalaHost> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        Path<String> path = root.<String>get("ip");
        Predicate equal = criteriaBuilder.equal(path, ip);
        return equal;
      }
    };
    Optional<KoalaHost> findOne = koalaHostRepository.findOne(specification);
    try {
      KoalaHost koalaHost = findOne.get();
      return koalaHost;
    } catch (Exception e) {
      return null;
    }
  }
}
